from fastapi import FastAPI
import uvicorn

from elasticsearch import Elasticsearch
from pydantic import BaseModel

clent = Elasticsearch(hosts="http://172.17.100.63:9200", http_auth=("elastic", "SnTgwq76ubmYyPO5"))

# 创建FastAPI应用
app = FastAPI()


class SearchItem(BaseModel):
    keyword: str


class ResultItem(BaseModel):
    data: list
    total: int


@app.post("/api/songling/search")
def songling_search(searchItem: SearchItem):
    keyword = searchItem.keyword
    from_idx = 0
    size = 5
    body = {
        "query": {
            "bool": {
                "should": [
                    {
                        "match": {
                            "title": "" + keyword + ""
                        }
                    },
                    {
                        "match": {
                            "contents.itemName": "" + keyword + ""
                        }
                    },
                    {
                        "match": {
                            "contents.detail": "" + keyword + ""
                        }
                    }
                ]
            }
        },
        "from": from_idx,
        "size": size
    }

    search = clent.search(index="knowledge", body=body)
    result = ResultItem(data=search["hits"]["hits"], total=search["hits"]["total"]["value"])
    print(result)
    return result


if __name__ == '__main__':
    uvicorn.run(app)
